import 'dart:developer';

import 'package:dio/dio.dart';
import 'package:edu/constants/app_strings.dart';
import 'package:edu/networks/course/models/course_response.dart';
import 'package:edu/utils/data_fetcher.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class CourseListPageLogic extends ChangeNotifier {
  late final ScrollController scrollController;

  final int? categoryId;
  final String? title;

  List<CourseBrief> courses = [];
  bool isLoading = false;
  bool isError = false;

  int? _lastPage;
  int _page = 1;
  int _pageSize = 20;

  bool get isCourseEmpty => courses.isEmpty;

  bool get canLoadMore {
    if (_lastPage != null) {
      return _page <= _lastPage!;
    } else {
      return true;
    }
  }

  CancelToken? _cancelToken;

  CourseListPageLogic({this.categoryId, this.title});

  void init() {
    scrollController = ScrollController();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        if (canLoadMore) {
          loadCourseList();
        }
      }
    });

    Future.delayed(Duration.zero, () {
      loadCourseList();
    });
  }

  @override
  void dispose() {
    _cancelToken?.cancel();
    scrollController.dispose();
    super.dispose();
  }

  void loadCourseList() async {
    try {
      if (isLoading) {
        return;
      }
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.black,
        dismissOnTap: false,
      );
      isLoading = true;
      isError = false;
      notifyListeners();

      _cancelToken ??= CancelToken();
      final response = await DataFetcher.shared.courseApi.getCourseList(
        categoryId: categoryId,
        page: _page,
        pageSize: _pageSize,
        cancelToken: _cancelToken,
      );
      isLoading = false;
      EasyLoading.dismiss();
      if (response.code == 0 && response.courses != null) {
        courses.addAll(response.courses!);
        _lastPage = response.pageMeta?.lastPage;
        _pageSize = response.pageMeta?.pageSize ?? 20;
        _page = ((response.pageMeta?.currentPage ?? _page) + 1);
      } else if (response.code != 0) {
        isError = true;
        EasyLoading.showError(response.message ?? AppStrings.courseListError);
      }
      notifyListeners();
    } on DioException catch (e) {
      EasyLoading.dismiss();
      if (e.type == DioExceptionType.cancel) {
        return;
      }
      isLoading = false;
      isError = true;
      EasyLoading.showError(e.toString());
      notifyListeners();
    } catch (e) {
      log('Error: $e');
    } finally {
      _cancelToken?.cancel();
      _cancelToken = null;
    }
  }
}
